<?php
namespace app\common\controller;

use app\common\controller\Api;
use think\Db;

class Commission extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 发放业务员佣金
     * $orderId 订单ID
     * $storeId 空间/中心ID
     */
    public function yeWuPrice($orderId,$storeId=1)
    {
        try {
            $salesmanLog = db('salesman_log')->where('order_id',$orderId)->whereOr('user_order_id',$orderId)->find();
            if (!empty($salesmanLog)) {
                //不能重复发佣金
                return false;
            }
            $orderInfo = db('order')->where(['id'=>$orderId])->find();
            if (empty($orderInfo)) {
                //订单不存在
                return false;
            }
            $orderType = $orderInfo['order_type'];

            if (in_array($orderType,[4,5])) {
                //采购订单
                $goodsStore_oid = 'cai_order_id';
                $goodsStore_goodsId = 'cai_order_goods_id';

                $salesman_oid = 'order_id';
            } else {
                //普通订单
                $goodsStore_oid = 'order_id';
                $goodsStore_goodsId = 'order_goods_id';

                $salesman_oid = 'user_order_id';
            }

            $yeWuPrice = 0;//业务佣金
            $yejiPrice = 0;//业务员业绩
            $bonusRatio = 0;//业务员奖金比例
            $salesmanId = 0;//业务员ID

            $orderGoods = db('order_goods')->where('order_id', $orderId)->select();
            foreach ($orderGoods AS $key => $value) {
                $goodsStore = db('order_goods_store')->where([$goodsStore_oid => $orderId, $goodsStore_goodsId => $value['id']])->select();
                foreach ($goodsStore AS $k => $v) {
                    $rate1 = $v['promotion_rate'];
                    if (!empty($v['center_store_id'])) {
                        //有中心上级
                        $rate1 = $v['promotion_rate']+$v['center_rate'];
                    }
                    $yeWuPrice += $v['salesman_price'];
                    $yejiPrice += $v['goods_price']-$v['pv']*($rate1/100);
                    $bonusRatio = $v['bonus_ratio'];
                    $salesmanId = $v['salesman_id'];
                }
            }

            //业务员佣金
            if (!empty($salesmanId)) {
                db('salesman_log')->insert([
                    'salesman_id' => $salesmanId,
                    $salesman_oid => $orderId,
                    'price' => $yeWuPrice,
                    'bonus_ratio' => $bonusRatio,
                    'yejiprice' => $yejiPrice,
                    'addtime' => time()
                ]);
            }
            return true;
        } catch (ValidateException|PDOException|Exception $e) {
            return false;
            $this->error($e->getMessage());
        }
    }

    /**
     * 发放推广佣金
     * $orderId 订单ID
     * $storeId 空间/中心ID
     */
    public function promotionPrice($orderId,$storeId)
    {
        try {
            $promitionLog = db('promition_log')->where('order_id',$orderId)->whereOr('user_order_id',$orderId)->find();
            if (!empty($promitionLog)) {
                //不能重复发佣金
                return false;
            }
            $orderInfo = db('order')->where(['id'=>$orderId])->find();
            if (empty($orderInfo)) {
                //订单不存在
                return false;
            }

            $orderType = $orderInfo['order_type'];
            $userId = $orderInfo['user_id'];//合伙人时用

            if (in_array($orderType,[4,5])) {
                //采购订单
                $goodsStore_oid = 'cai_order_id';
                $goodsStore_goodsId = 'cai_order_goods_id';

                $promition_oid = 'order_id';
            } else {
                //普通订单
                $goodsStore_oid = 'order_id';
                $goodsStore_goodsId = 'order_goods_id';

                $promition_oid = 'user_order_id';
            }

            $store = db('store')->where('id', $storeId)->find();
            $orderGoods = db('order_goods')->where('order_id', $orderId)->select();
            $promotion_price_pt = 0;//推广人佣金
            $promotionRate = 0;//推广人推广比例
            $centerStoreId = 0;//上级中心ID
            $centerPrice = 0;//上级中心推广费
            $promotionType = 0;
            $promotionId = 0;//推广人ID
            $centerRate = 0;//上级中心推广比例
            $promotionIdPartner = 0;//合伙人的推广人ID
            $promotionTypePartner = 0;//合伙人的推广人角色
            $promotionPrice = 0;//合伙人的推广人佣金
            $promotionRatePartner = 0;//合伙人的推广人比例

            $partnerdata=[];

            foreach ($orderGoods AS $key => $value) {
         
                $goodsStore = db('order_goods_store')->where([$goodsStore_oid => $orderId, $goodsStore_goodsId => $value['id'],'isfa'=>'0','authen'=>['in','0,3']])->select();

                foreach ($goodsStore AS $k => $v) {
                    $promotion_price_pt += $v['promotion_price_pt'];
                    $centerPrice += $v['center_price'];
                    

                    $promotionType = $v['promotion_type'];
                    $promotionId = $v['promotion_id'];
                    $promotionRate = $v['promotion_rate'];
                    $centerRate = $v['center_rate'];
                    $centerStoreId = $v['center_store_id'];

                    if($v['promotion_price']>0)
                    {
                        
                        $promotionPrice+=$v['promotion_price'];
                        $promotionIdPartner = $v['promotion_id_partner'];
                        $promotionTypePartner = $v['promotion_type_partner'];
                        $promotionRatePartner = $v['promotion_rate_partner'];



                        if (!isset($partnerdata[$v['promotion_id_partner']])) {  
                            // 如果不存在，则初始化该键对应的数组，并设置'price'为0  
                            // $partnerdata[$v['promotion_id_partner']] = ['price' => 0];  
                            $partnerdata[$v['promotion_id_partner']] = ['promotionPrice' => 0,'promotionIdPartner' => 0,'promotionTypePartner' => 0,'promotionRatePartner' => 0,'order_id' => 0];   
                        }  
                  
                        // 累加
                        $partnerdata[$v['promotion_id_partner']]['promotionPrice']+=$v['promotion_price'];
                        $partnerdata[$v['promotion_id_partner']]['promotionIdPartner']=$v['promotion_id_partner'];
                        $partnerdata[$v['promotion_id_partner']]['promotionTypePartner']=$v['promotion_type_partner'];
                        $partnerdata[$v['promotion_id_partner']]['promotionRatePartner']=$v['promotion_rate_partner'];
                        $partnerdata[$v['promotion_id_partner']]['order_id']=$v['order_id'];
                    }
                    

                }
            }
            //var_dump($promotionIdPartner);die;
            //推广佣金
            if (!empty($promotionId)) {
                db('promition_log')->insert([
                    'promotion_type' => $promotionType,
                    'promotion_id' => $promotionId,
                    'promotion_type2' => $store['type'],
                    'promotion_id2' => $storeId,
                    $promition_oid => $orderId,
                    'price' => $promotion_price_pt,
                    'rate' => $promotionRate,
                    'type' =>1,
                    'user_del' => 0,
                    'addtime' => time()
                ]);

                //更新账户余额
                if ($promotionType == 1 || $promotionType == 2) {
                    db('store')->where('id', $promotionId)->lock(true)->find();
                    db('store')->where('id', $promotionId)->setInc('promotion_money', $promotion_price_pt);
                } else {
                    db('user')->where('id', $promotionId)->lock(true)->find();
                    db('user')->where('id', $promotionId)->setInc('promotion_money', $promotion_price_pt);
                }    
            }

            //不用判断复购，order_goods_store加数据的时候判断了
            if (!empty($centerStoreId) && $centerStoreId !== $promotionId && $centerPrice>0) {
                //推广佣金--有中心时给中心一笔
                db('promition_log')->insert([
                    'promotion_type' => 1,
                    'promotion_id' => $centerStoreId,
                    'promotion_type2' => $store['type'],
                    'promotion_id2' => $storeId,
                    $promition_oid => $orderId,
                    'price' => $centerPrice,
                    'rate' => $centerRate,
                    'type' =>1,
                    'user_del' => 0,
                    'addtime' => time()
                ]);
                //更新账户余额
                db('store')->where('id', $centerStoreId)->lock(true)->find();
                db('store')->where('id', $centerStoreId)->setInc('promotion_money', $centerPrice);
            }

            foreach ($partnerdata as $partnerId => $partnerInfo) {  
                //合伙人采购的下单人id
                $userId=db('order')->where('id',$partnerInfo['order_id'])->value('user_id');
                if ($partnerInfo['promotionPrice']>0) {
                    db('promition_log')->insert([
                        'promotion_type'=>$partnerInfo['promotionTypePartner'],
                        'promotion_id'=>$partnerInfo['promotionIdPartner'],
                        'promotion_type2'=>3,
                        'promotion_id2'=>$userId,
                        $promition_oid=>$orderId,
                        'price'=>$partnerInfo['promotionPrice'],
                        'rate'=>$promotionRatePartner,
                        'type'=>1,
                        'store_id'=>$storeId,
                        'addtime'=>time()
                    ]);
                    //更新账户余额
                    if ($partnerInfo['promotionTypePartner'] == 1 || $partnerInfo['promotionTypePartner'] == 2) {
                        db('store')->where('id',$partnerInfo['promotionIdPartner'])->lock(true)->find();
                        db('store')->where('id',$partnerInfo['promotionIdPartner'])->setInc('promotion_balance',$partnerInfo['promotionPrice']);
                    } else {
                        db('user')->where('id',$partnerInfo['promotionIdPartner'])->lock(true)->find();
                        db('user')->where('id',$partnerInfo['promotionIdPartner'])->setInc('promotion_balance',$partnerInfo['promotionPrice']);
                    }
                }
            }
            return true;
        } catch (ValidateException|PDOException|Exception $e) {
            return false;
            $this->error($e->getMessage());
        }
    }
    /**
     * 发放推广佣金,转化模式的时候用
     * $orderId 订单ID
     * $storeId 空间/中心ID
     */
    public function promotionPrice_zhuan($orderId,$storeId)
    {
        try {
            $promitionLog = db('promition_log')->where('order_id',$orderId)->whereOr('user_order_id',$orderId)->find();
            if (!empty($promitionLog)) {
                //不能重复发佣金
                return false;
            }
            $orderInfo = db('order')->where(['id'=>$orderId])->find();
            if (empty($orderInfo)) {
                //订单不存在
                return false;
            }

            $orderType = $orderInfo['order_type'];
            $userId = $orderInfo['user_id'];//合伙人时用

            if (in_array($orderType,[4,5])) {
                //采购订单
                $goodsStore_oid = 'cai_order_id';
                $goodsStore_goodsId = 'cai_order_goods_id';

                $promition_oid = 'order_id';
            } else {
                //普通订单
                $goodsStore_oid = 'order_id';
                $goodsStore_goodsId = 'order_goods_id';

                $promition_oid = 'user_order_id';
            }

            $store = db('store')->where('id', $storeId)->find();
            $orderGoods = db('order_goods')->where('order_id', $orderId)->select();
            $promotion_price_pt = 0;//推广人佣金
            $promotionRate = 0;//推广人推广比例
            $centerStoreId = 0;//上级中心ID
            $centerPrice = 0;//上级中心推广费
            $promotionType = 0;
            $promotionId = 0;//推广人ID
            $centerRate = 0;//上级中心推广比例
            $promotionIdPartner = 0;//合伙人的推广人ID
            $promotionTypePartner = 0;//合伙人的推广人角色
            $promotionPrice = 0;//合伙人的推广人佣金
            $promotionRatePartner = 0;//合伙人的推广人比例

            $partnerdata=[];

            foreach ($orderGoods AS $key => $value) {
           
                $goodsStore = db('order_goods_store')->where([$goodsStore_oid => $orderId, $goodsStore_goodsId => $value['id'],'isfa'=>'0','authen'=>['in','0,3']])->select();

                foreach ($goodsStore AS $k => $v) {
                    $promotion_price_pt += $v['promotion_price_pt'];
                    $centerPrice += $v['center_price'];
                    

                    $promotionType = $v['promotion_type'];
                    $promotionId = $v['promotion_id'];
                    $promotionRate = $v['promotion_rate'];
                    $centerRate = $v['center_rate'];
                    $centerStoreId = $v['center_store_id'];

                    if($v['promotion_price']>0)
                    {
                        
                        $promotionPrice+=$v['promotion_price'];
                        $promotionIdPartner = $v['promotion_id_partner'];
                        $promotionTypePartner = $v['promotion_type_partner'];
                        $promotionRatePartner = $v['promotion_rate_partner'];



                        if (!isset($partnerdata[$v['promotion_id_partner']])) {  
                            // 如果不存在，则初始化该键对应的数组，并设置'price'为0  
                            // $partnerdata[$v['promotion_id_partner']] = ['price' => 0]; 
                            $partnerdata[$v['promotion_id_partner']] = ['promotionPrice' => 0,'promotionIdPartner' => 0,'promotionTypePartner' => 0,'promotionRatePartner' => 0,'order_id' => 0];   
                        }  
                  
                        // 累加
                        $partnerdata[$v['promotion_id_partner']]['promotionPrice']+=$v['promotion_price'];
                        $partnerdata[$v['promotion_id_partner']]['promotionIdPartner']=$v['promotion_id_partner'];
                        $partnerdata[$v['promotion_id_partner']]['promotionTypePartner']=$v['promotion_type_partner'];
                        $partnerdata[$v['promotion_id_partner']]['promotionRatePartner']=$v['promotion_rate_partner'];
                        $partnerdata[$v['promotion_id_partner']]['order_id']=$v['order_id'];
                    }
                    

                }
            }
            //var_dump($promotionIdPartner);die;
            //推广佣金
            if (!empty($promotionId)) {
                db('promition_log')->insert([
                    'promotion_type' => $promotionType,
                    'promotion_id' => $promotionId,
                    'promotion_type2' => $store['type'],
                    'promotion_id2' => $storeId,
                    $promition_oid => $orderId,
                    'price' => $promotion_price_pt,
                    'rate' => $promotionRate,
                    'type' =>1,
                    'user_del' => 0,
                    'addtime' => time()
                ]);

                //更新账户余额
                if ($promotionType == 1 || $promotionType == 2) {
                    db('store')->where('id', $promotionId)->lock(true)->find();
                    db('store')->where('id', $promotionId)->setInc('promotion_money', $promotion_price_pt);
                } else {
                    db('user')->where('id', $promotionId)->lock(true)->find();
                    db('user')->where('id', $promotionId)->setInc('promotion_money', $promotion_price_pt);
                }

                
            }

            //不用判断复购，order_goods_store加数据的时候判断了
            if (!empty($centerStoreId) && $centerStoreId !== $promotionId && $centerPrice>0) {
                //推广佣金--有中心时给中心一笔
                db('promition_log')->insert([
                    'promotion_type' => 1,
                    'promotion_id' => $centerStoreId,
                    'promotion_type2' => $store['type'],
                    'promotion_id2' => $storeId,
                    $promition_oid => $orderId,
                    'price' => $centerPrice,
                    'rate' => $centerRate,
                    'type' =>1,
                    'user_del' => 0,
                    'addtime' => time()
                ]);
                //更新账户余额
                db('store')->where('id', $centerStoreId)->lock(true)->find();
                db('store')->where('id', $centerStoreId)->setInc('promotion_money', $centerPrice);
            }
            
            return true;
        } catch (ValidateException|PDOException|Exception $e) {
            return false;
            $this->error($e->getMessage());
        }
    }

    /**
     * 发放推广佣金，采购模式下，合伙人采购单确认收货时用 核销模式还是走promotionPrice
     * $orderId 订单ID
     * $storeId 空间/中心ID
     */
    public function promotionPrice_cai($orderId,$storeId)
    {
        try {
            $promitionLog = db('promition_log')->where('order_id',$orderId)->whereOr('user_order_id',$orderId)->find();
            if (!empty($promitionLog)) {
                //不能重复发佣金
                return false;
            }
            $orderInfo = db('order')->where(['id'=>$orderId])->find();
            if (empty($orderInfo)) {
                //订单不存在
                return false;
            }

            $orderType = $orderInfo['order_type'];
            $userId = $orderInfo['user_id'];//合伙人时用

            if (in_array($orderType,[4,5])) {
                //采购订单
                $goodsStore_oid = 'cai_order_id';
                $goodsStore_goodsId = 'cai_order_goods_id';

                $promition_oid = 'order_id';
            } else {
                //普通订单
                $goodsStore_oid = 'order_id';
                $goodsStore_goodsId = 'order_goods_id';

                $promition_oid = 'user_order_id';
            }

            $store = db('store')->where('id', $storeId)->find();
            $orderGoods = db('order_goods')->where('order_id', $orderId)->select();
            $promotion_price_pt = 0;//推广人佣金
            $promotionRate = 0;//推广人推广比例
            $centerStoreId = 0;//上级中心ID
            $centerPrice = 0;//上级中心推广费
            $promotionType = 0;
            $promotionId = 0;//推广人ID
            $centerRate = 0;//上级中心推广比例
            $promotionIdPartner = 0;//合伙人的推广人ID
            $promotionTypePartner = 0;//合伙人的推广人角色
            $promotionPrice = 0;//合伙人的推广人佣金
            $promotionRatePartner = 0;//合伙人的推广人比例

            $partnerdata=[];

            foreach ($orderGoods AS $key => $value) {
              
                $goodsStore = db('order_goods_store')->where([$goodsStore_oid => $orderId, $goodsStore_goodsId => $value['id']])->select();

                foreach ($goodsStore AS $k => $v) {
                    $promotion_price_pt += $v['promotion_price_pt'];
                    $centerPrice += $v['center_price'];
                    

                    $promotionType = $v['promotion_type'];
                    $promotionId = $v['promotion_id'];
                    $promotionRate = $v['promotion_rate'];
                    $centerRate = $v['center_rate'];
                    $centerStoreId = $v['center_store_id'];

                    if($v['promotion_price']>0)
                    {
                        
                        $promotionPrice+=$v['promotion_price'];
                        $promotionIdPartner = $v['promotion_id_partner'];
                        $promotionTypePartner = $v['promotion_type_partner'];
                        $promotionRatePartner = $v['promotion_rate_partner'];



                        if (!isset($partnerdata[$v['promotion_id_partner']])) {  
                            // 如果不存在，则初始化该键对应的数组，并设置'price'为0  
                       
                            $partnerdata[$v['promotion_id_partner']] = ['promotionPrice' => 0,'promotionIdPartner' => 0,'promotionTypePartner' => 0,'promotionRatePartner' => 0,'order_id' => 0];  
                        }  
                        // var_dump($partnerdata[$v['promotion_id_partner']]);
                  
                        // 累加
                        $partnerdata[$v['promotion_id_partner']]['promotionPrice']+=$v['promotion_price'];
                        $partnerdata[$v['promotion_id_partner']]['promotionIdPartner']=$v['promotion_id_partner'];
                        $partnerdata[$v['promotion_id_partner']]['promotionTypePartner']=$v['promotion_type_partner'];
                        $partnerdata[$v['promotion_id_partner']]['promotionRatePartner']=$v['promotion_rate_partner'];
                        $partnerdata[$v['promotion_id_partner']]['order_id']=$v['order_id'];
                    }
                    

                }
            }

            //合伙人的推广人佣金
            if (!empty($promotionIdPartner)) {
                db('promition_log')->insert([
                    'promotion_type'=>$promotionTypePartner,
                    'promotion_id'=>$promotionIdPartner,
                    'promotion_type2'=>3,
                    'promotion_id2'=>$userId,
                    $promition_oid=>$orderId,
                    'price'=>$promotionPrice,
                    'rate'=>$promotionRatePartner,
                    'type'=>1,
                    'store_id'=>$storeId,
                    'addtime'=>time()
                ]);
                //更新账户余额
                if ($promotionTypePartner == 1 || $promotionTypePartner == 2) {
                    db('store')->where('id',$promotionIdPartner)->lock(true)->find();
                    db('store')->where('id',$promotionIdPartner)->setInc('promotion_balance',$promotionPrice);
                } else {
                    db('user')->where('id',$promotionIdPartner)->lock(true)->find();
                    db('user')->where('id',$promotionIdPartner)->setInc('promotion_balance',$promotionPrice);
                }
            }

            return true;
        } catch (ValidateException|PDOException|Exception $e) {
            return false;
            $this->error($e->getMessage());
        }
    }


    /**
     * 发放分销佣金
     * @path api/search/Search/searchHot
     */
    public function fenxiaoPrice()
    {
        //return ['ll'=>$a];
    }
}
